//
//  KLSGRadioListViewController.m
//  KaoLaShiGuangFM
//
//  Created by lanou3g on 15/10/28.
//  Copyright © 2015年 com.lanou3g. All rights reserved.
//

#import "KLSGRadioListViewController.h"
#import "KLSGRadioTableViewCell.h"
#import "KLSGPlayRadioViewController.h"
#import "KLSGDataFail.h"

@interface KLSGRadioListViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) KLSGDataFail *dataFailView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *allDataArray;

@end

@implementation KLSGRadioListViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self addSubViews];
    [self setUpData];
    [self setupRefresh];
    
}

#pragma mark - 下拉刷新
- (void)setupRefresh
{
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    [self.tableView headerBeginRefreshing];
    self.tableView.headerPullToRefreshText = @"下拉可以刷新";
    self.tableView.headerRefreshingText = @"正在加载";
    self.tableView.headerReleaseToRefreshText = @"松开马上刷新";
    
}
- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setUpData];
        [self.tableView headerEndRefreshing];
    });
}

#pragma mark - 解析数据
- (void)setUpData
{
    
    // 1.创建session对象  NSURLSession
    NSURLSession *session = [NSURLSession sharedSession];
    // 2.创建网址对象
    NSString *urlStr = nil;
    if (self.buttonTag == 0) {
        urlStr = kLocalAPI;
    } else if (self.buttonTag == 2) {
        urlStr = kCountryAPI;
    } else if (self.buttonTag == 3) {
        urlStr = kWebAPI;
    }
    
    NSURL *url = [NSURL URLWithString:urlStr];
    
    // 3.根据URL创建请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 4.建立会话 NSURLSessionDataTask
    // block中要使用self 需要用__block修饰一下
    __block KLSGRadioListViewController *mySelf = self;
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        // 5.解析
        if (data != nil) {
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            // 取出需要的数据
            NSArray *resultArray = dic[@"result"];
            
            // 初始化数组
            mySelf.allDataArray = [NSMutableArray array];
            // 遍历数组给model赋值,并保存到数组中
            for (NSDictionary *dic in resultArray) {
                KLSGRadioModel *model = [[KLSGRadioModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [mySelf.allDataArray addObject:model];
            }
            
            // 回到主线程刷新
            [mySelf performSelectorOnMainThread:@selector(reloadData:) withObject:self.tableView waitUntilDone:YES];
            
        } else {
            [mySelf performSelectorOnMainThread:@selector(failAction) withObject:nil waitUntilDone:YES];
        }
        
    }];
    
    // 6.启动解析
    [task resume];
}

#pragma mark - 重新加载数据
- (void)failAction
{
    self.dataFailView = [[KLSGDataFail alloc] initWithFrame:CGRectMake(0, 10, kScreenWidth, 300)];
    self.tableView.tableFooterView = _dataFailView;
    [self.dataFailView netRequestFailWithBlock:^{
        [self setUpData];
        [_dataFailView hidden];
    }];
}

#pragma mark - 刷新
- (void)reloadData:(UITableView *)tableView
{
    [tableView reloadData];
}

#pragma mark - UI布局
- (void)addSubViews
{
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    // tableView去除cell之间的线
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self.tableView.bounces = NO;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    
    // 设置leftBarButton
    UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemReply) target:self action:@selector(leftReturn)];
    left.tintColor = [UIColor colorWithRed:234 / 256.0 green:79 / 256.0 blue:56 / 256.0 alpha:1];
    self.navigationItem.leftBarButtonItem = left;
}

- (void)leftReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - tableView代理方法
#pragma mark - 返回分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark - 返回分区行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allDataArray.count;
}

#pragma mark - 返回cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"MyCell";
    KLSGRadioTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[KLSGRadioTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    // 显示数据
    if (self.allDataArray.count > 0) {
        // 通过下标获取model
        KLSGRadioModel *model = self.allDataArray[indexPath.row];
        // 给model赋值
        cell.model = model;
    }
    
    return cell;
}

#pragma mark - 返回行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

#pragma mark - 点击cell跳转详情界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
    KLSGPlayRadioViewController *playViewController = (KLSGPlayRadioViewController *)appDelegate.playVC;
    // 根据位置得到model
    KLSGRadioModel *model = self.allDataArray[indexPath.row];
    // 电台标题
    playViewController.rname = model.rname;
    playViewController.radioId = model.radioId;
    // radioModel数组
    playViewController.radioModelArray = self.allDataArray;
    // 获取当前点击下标
    playViewController.index = indexPath.row;
    playViewController.type = VoiceTypeRadio;
    [self presentViewController:playViewController animated:YES completion:nil];
}

#pragma mark - 延迟加载
- (NSMutableArray *)allDataArray
{
    if (!_allDataArray) {
        _allDataArray = [NSMutableArray array];
    }
    return _allDataArray;
}

- (KLSGDataFail *)dataFailView
{
    if (!_dataFailView) {
        _dataFailView = [[KLSGDataFail alloc] init];
    }
    return _dataFailView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
